package com.xc.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xc.demo.entity.Role;
import com.xc.demo.entity.RoleMenu;
import com.xc.demo.mapper.RoleMapper;
import com.xc.demo.mapper.RoleMenuMapper;
import com.xc.demo.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

//    先删后增
//    事务注解，保证下面功能同时成功同时失败
    @Transactional
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {

//        首先当前角色id绑定的所有绑定菜单关系
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        roleMenuMapper.delete(queryWrapper);

//        再把前端传过来的菜单id绑定到该角色上

        for(Integer menuId : menuIds){
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRole_id(roleId);
            roleMenu.setMenu_id(menuId);
            roleMenuMapper.insert(roleMenu);
        }



    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }


}
